package com.yc.hwc.web;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import com.yc.hwc.bean.Result;
import com.yc.hwc.bean.User;
import com.yc.util.Utils;

@Controller
@RequestMapping(path = { "hwcindex", "/" })
public class UploadDo {

	@Value("${upload-dir}")
	private String uploadDir;

	// 特殊字符+空白符
	private static final String CHAR_REGEX = "[\\s`~!@#$%^&*()+=<>?:\"{}|,\\/;'\\[\\]·~！@#￥%……&*（）——\\-+={}|《》？：“”【】、；‘'，。、]";

	@PostMapping("upload")
	@ResponseBody
	Result<?> upload(@RequestParam("file") MultipartFile mf, @SessionAttribute(required = false) User loginedUser) {
		String path = uploadDir;
		String webpath = "";
		String name = mf.getOriginalFilename().replaceAll(CHAR_REGEX, "_");
		if (loginedUser != null) {
			webpath = loginedUser.getClsSn() + "/" + loginedUser.getName() + "/";
			path += webpath;
		} else {
			int i = name.lastIndexOf(".");
			String suffix = null;
			if (i > 0) {
				suffix = name.substring(i);
			}
			name = UUID.randomUUID().toString().replaceAll("-", "");
			name += suffix != null ? suffix : "";

		}
		File dir = new File(path);
		if (dir.exists() == false && dir.mkdirs() == false) {
			System.out.println("创建上传目录失败:" + dir);
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.success("创建上传目录失败！", null);
		}
		if("image.png".equals(name)) {
			// ueditor 截图粘贴文件上传的固定格式是 image.png, 所以要改名
			name = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
		}
		File file = new File(dir, name);
		try {
			mf.transferTo(file);
			Object ret = Utils.toMap(
					// Upload 对象字段
					"webPath", webpath + name, "oldName", name, "newName", name, "RelaTable", "task_log",
					// Layui 富文本编辑需要字段
					"src", webpath + name, "title", name);
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.failure("文件上传成功！", ret);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			/** layedit 0 表示成功， 其它表示失败 **/
			return Result.success("文件上传失败！", null);
		}

	}

}
